#include <iostream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>

int main(int argc, char* argv[])
{
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        exit(1);
    }

    sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    server.sin_port = htons(port);

    int n = bind(sockfd, (sockaddr*)&server, sizeof server);

    // char buffer[1024]; //用string 防止溢出
    while(true)
    {
        std::string buffer;
        std::cout << "client enter: ";
        std::getline(std::cin, buffer);
        int n = sendto(sockfd, buffer.c_str(), buffer.size(), 0, (sockaddr*)&server, sizeof server);
        if(n > 0)
        {
            sockaddr_in temp;
            memset(&temp, 0, sizeof temp);
            socklen_t len = sizeof temp;
            char rebuffer[1024];
            // int m = recvfrom(sockfd, (void*)buffer.c_str(), 1024, 0, (sockaddr*)&temp, &len);
            int m = recvfrom(sockfd, rebuffer, sizeof rebuffer, 0, (sockaddr*)&temp, &len);
            if(m > 0)
            {
                rebuffer[m] = 0;
                std::cout << rebuffer << std::endl;
            }
        }        
    }
}
